package list;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * list对象转换为对应的VO
 * @author ycc
 * @date 2024/7/22
 */
public class ListConvert {
    public static void main(String[] args) {
        ListConvert listConvert = new ListConvert();
        listConvert.test();
    }

    public void test() {
        List<Person> list = new ArrayList<>();
        list.add(new Person(1L, "张三", 20));
        list.add(new Person(2L, "李四", 30));
        list.add(new Person(3L, "王五", 40));
        // 转换为VO
        List<PersonVO> voList = convertObj(list, PersonVO.class);
        System.out.println(voList);
    }

    /**
     * 转换list对象到相应的VO
     * @param list
     * @param clazz
     * @return
     * @param <T1>
     * @param <T2>
     */
    public <T1, T2> List<T2> convertObj(List<T1> list, Class<T2> clazz) {

        return list.stream().map(item -> {
            T2 obj;
            try {
                obj = clazz.getDeclaredConstructor().newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }

            BeanUtils.copyProperties(item, obj);
            return obj;
        }).collect(Collectors.toList());
    }

    public class Person {
        private Long id;
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Person(Long id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }

    /**
     * 创建静态测试内部类
     */
    public static class PersonVO {
        private Long id;
        private String name;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String toString() {
            return "PersonVO{" +
                    "id=" + this.id +
                    ", name='" + this.name + '\'' +
                    '}';
        }
    }
}
